<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BApplication
 *
 * @author jianfeng
 */
class BUser {

    const WORKTEAMADMINROLE = "workteam_admin";
    const WORKTEAMMEMBERROLE = "workteam_member";
    const SERVEDTEAMADMINROLE = "servedteam_admin";
    const SERVEDTEAMMEMBERROLE = "servedteam_member";
    const SERVICEMIXEDROLE = "service_mixed";
    const SERVICENONEROLE = "service_none";
    const TransitVariable_UserServicesOfRoleType = "userServicesOfRoleType";

    private $personalService = null;
    private $services = array();
    private $_identity = null;
    private $_userId = null;
    private $servicesWithRoles = array();

    public function __construct($userId = null) {
        $this->load($userId);
    }

    protected function load($userId) {
        if ($userId != null)
            $this->_userId = $userId;
    }

    /**
     *
     * @param type $serviceId
     * @param type $config
     * @return BService 
     */
    public function getPersonalService() {
        if ($this->personalService == null)
            $this->personalService = new BService(null, BService::PERSONALSERVICETYPE, array('UserId' => $this->getId()));
        return $this->personalService;
    }

    public function getCurrentUserServices($roleType) {

        $db = Blyn::app()->getAppDb();

        /**
         * by add userservices into transit variable to improve performance,
         * if not set reload setting, will try to get user services from saved
         * transit variable, if make change to user services such as add user's services
         * should set "isReloadUserServices" to true
         */
        $services = $this->getTransitVariable(self::TransitVariable_UserServicesOfRoleType);
        $services = NULL;

        if ($services == NULL)
            $services = array();

        if (!isset($services[$roleType]))
            $services[$roleType] = array();

        if ($services[$roleType] == NULL) {
            //$this->services = $db->getUserServices($this->getId(), $roleType);
            $this->servicesWithRoles = $this->getCurrentUserServicesWithRoles();

            foreach ($this->servicesWithRoles as $serviceId => $serviceWithRoles) {
                $rolesId = $serviceWithRoles['rolesId'];

                foreach ($rolesId as $roleId) {
                    if ($db->isRoleTypeOf($roleId, $serviceId, $roleType))
                        $services[$roleType][$serviceId] = $serviceWithRoles['service'];
                }
            }

            $this->services = $services;

            if ($services[$roleType] != NULL) {
                $this->addTransitVariable(self::TransitVariable_UserServicesOfRoleType, $services);
            }
        } else {
            $this->services = $services;
        }

        return $this->services[$roleType];
    }

    /**
     *
     * @return mix, return service with a roleId list
     * forexample, return value = array(
     * '33'=>array('service'=>service1,rolesId=array("role id list"))
     */
    public function getCurrentUserServicesWithRoles() {
        if ($this->servicesWithRoles == NULL) {
            $services = Blyn::app()->getAppDb()->getUserServicesWithRoles($this->getId());
            foreach ($services as $serviceId => $rolesId) {
                $this->servicesWithRoles[$serviceId] = array('service' => new BService($serviceId), 'rolesId' => $rolesId);
            }
        }

        return $this->servicesWithRoles;
    }

    public function getCurrentUserServiceByName($name) {
        $servicesWithRoles = $this->getCurrentUserServicesWithRoles();

        foreach ($servicesWithRoles as $serviceWithRole) {
            $service = $serviceWithRole['service'];
            if ($service->getName() == $name)
                return $service;
        }

        return FALSE;
    }

    public function getCurrentUserServiceById($serviceId) {
        $servicesWithRoles = $this->getCurrentUserServicesWithRoles();

        return $servicesWithRoles[$serviceId]['service'];
    }

    public function getId() {

        $user = $this->getWebUser();

        if ($user != null) {
            $id = $user->getId();

            if ($id != null)
                return $id;
        }

        return $this->_userId;
    }

    public function getLoginId() {

        if ($this->_userId == NULL) {
            $user = $this->getWebUser();
            $id = $user->getId();
        } else {
            $id = $this->_userId;
        }

        $userData = Blyn::app()->getAppDb()->getUserById($id);

        return $userData['email'];
    }

    /**
     *
     * @return CWebUser
     */
    protected function getWebUser() {

        return yii::app()->user;
    }

    public function login($loginId, $email, $password, $duration) {

        if ($this->_identity === null) {
            $this->_identity = new BUserIdentity($loginId, $email, $password);
            $this->_identity->authenticate();
        }
        if ($this->_identity->errorCode === BUserIdentity::ERROR_NONE) {
            $this->getWebUser()->login($this->_identity, $duration);
            return true;
        }
        else
            return false;
    }

    public function register($loginId, $email, $password, $birthday, $profile) {
        $appDb = new BAppDb();

        $userId = $appDb->createUser($loginId, $email, $password, $birthday, $profile);
        $this->load($userId);

        //add personalService
        if ($userId != FALSE) {

            if ($email === "bAdmin@bilyn.com") {
                $bApp = new BilynAdminApp(null, FALSE);
                $bApp->registerSystemApps();

                $bAdminService = BService::createService(array("User" => $this, "ServiceName" => "BilynAdmin",
                            'ServiceType' => BService::NORMALSERVICETYPE));

                $bAdminService->getServiceEngine()->doOperation(BServiceEngine::ADDSERVICEAPPOPERATION, array('Service' => $bAdminService, 'App' => new BilynAdminApp()));
            }

            $pService = BService::createService(array("User" => $this, "ServiceName" => $userId . "_personalService",
                        'ServiceType' => BService::PERSONALSERVICETYPE));

            //add default app into personalService      
            $pApp = new BPersonalApp();
            $pService->getServiceEngine()->doOperation(BServiceEngine::ADDSERVICEAPPOPERATION, array('Service' => $pService, 'App' => $pApp));
            //$pService->getServiceEngine()->doOperation(BServiceEngine::ADDSERVICEAPPOPERATION, array('Service' => $pService, 'App' => $pApp));
//            $pMessageApp = new BPersonalMessageApp();
//            $pService->getServiceEngine()->doOperation(BServiceEngine::ADDSERVICEAPPOPERATION, array('Service' => $pService, 'App' => $pMessageApp));

            /*
              $pEventApp = new BPersonalEventApp();
              $pService->getServiceEngine()->doOperation(BServiceEngine::ADDSERVICEAPPOPERATION, array('Service' => $pService, 'App' => $pEventApp));

              $pInfoApp = new BPersonalInfoApp();
              $pService->getServiceEngine()->doOperation(BServiceEngine::ADDSERVICEAPPOPERATION, array('Service' => $pService, 'App' => $pInfoApp));

              $pCircleApp = new BPersonalCircleApp();
              $pService->getServiceEngine()->doOperation(BServiceEngine::ADDSERVICEAPPOPERATION, array('Service' => $pService, 'App' => $pCircleApp));
             */
            return TRUE;
            //      $this->login($loginId, $email, $password, $duration);
        }
        return FALSE;
    }

    public function authenticate($loginId, $email, $password) {
        if ($this->_identity == null)
            $this->_identity = new BUserIdentity($loginId, $email, $password);
        return $this->_identity->authenticate();
    }

    public function addTransitVariable($name, $value, $scope = null, $type = NULL) {

        $userId = $this->getId();

        if ($scope == NULL)
            $scope = 'u' . $userId . '_';


        $db = Blyn::app()->getAppDb();

        $value = serialize($value);

        $db->addTransitVariable($name, $value, $scope, $type);
    }

    public function getTransitVariable($name, $scope = NULL, $type = NULL) {

        $retValue = FALSE;

        $userId = $this->getId();

        if ($scope == NULL)
            $scope = 'u' . $userId . '_';

        $db = Blyn::app()->getAppDb();

        $value = $db->getTransitVariable($name, $scope, $type);

        if (isset($value) && $value != NULL) {
            $retValue = unserialize($value);
            return $retValue;
        }

        return $retValue;
    }

    public function resetTransitVariable($name = null, $scope = NULL, $scopeType = null) {
        $userId = $this->getId();

        if ($scope == NULL)
            $scope = 'u' . $userId . '_';

        $db = Blyn::app()->getAppDb();

        $db->deleteTransitVariable($scope, $name, $scopeType);
    }

}

?>
